let currentDomain = window.location.hostname;
let base_domain = '.norincogroup-ebuy.com';
let access_token_postFix = '.access_token';
let user_id_postFix = '.userid';
let MarketPrefix = 'Market';
let ManagerPrefix = 'Manager';

let env = 'DEV';
if(currentDomain.indexOf('ispacechina.com')>-1){
    env = 'TEST';
}
if(currentDomain.indexOf('test.norincogroup-ebuy.com')>-1){
    env = 'TEST';
}
if(currentDomain.indexOf('.dev.norincogroup-ebuy.com')>-1){
    env = 'DEV';
}

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        // console.log(request)
      if (request.type == "cookieChange") {
        // console.log('cookie 变更事件');
        initAndUpdateToken();
      }
      return true;
    }
  );

function initAndUpdateToken(){
    // console.log('检查和更新 token')
    let HT_TOKENS = {
        FRONT:{
            token: MarketPrefix + '.ht' + '.' + env.toLowerCase() + base_domain + access_token_postFix,
            userId: MarketPrefix + '.ht' + '.' + env.toLowerCase() + base_domain + user_id_postFix
        },
        BACK:{
            token: ManagerPrefix + '.ht' + '.' + env.toLowerCase() + base_domain + access_token_postFix,
            userId: ManagerPrefix + '.ht' + '.' + env.toLowerCase() + base_domain + user_id_postFix
        }
    };
    
    let BQ_TOKENS = {
        FRONT:{
            token: MarketPrefix + '.' + env.toLowerCase() + base_domain + access_token_postFix,
            userId: MarketPrefix + '.' + env.toLowerCase() + base_domain + user_id_postFix
        },
        BACK:{
            token: ManagerPrefix + '.' + env.toLowerCase() + base_domain + access_token_postFix,
            userId: ManagerPrefix + '.' + env.toLowerCase() + base_domain + user_id_postFix
        }
    };

    let tokenfrontHT = {
        'userId':Cookies.get(HT_TOKENS.FRONT.userId),
        'token':Cookies.get(HT_TOKENS.FRONT.token),
        'env':env+'_F_HT'
    }
    let tokenBackHT = {
        'userId':Cookies.get(HT_TOKENS.BACK.userId),
        'token':Cookies.get(HT_TOKENS.BACK.token),
        'env':env+'_B_HT'
    }

    let tokenfrontBQ = {
        'userId':Cookies.get(BQ_TOKENS.FRONT.userId),
        'token':Cookies.get(BQ_TOKENS.FRONT.token),
        'env':env+'_F_BQ'
    }
    let tokenBackBQ = {
        'userId':Cookies.get(BQ_TOKENS.BACK.userId),
        'token':Cookies.get(BQ_TOKENS.BACK.token),
        'env':env+'_B_BQ'
    }

    if(tokenfrontHT.userId){
        saveOrUpdate(env, tokenfrontHT);
    }
    if(tokenBackHT.userId){
        saveOrUpdate(env, tokenBackHT);
    }
    if(tokenfrontBQ.userId){
        saveOrUpdate(env, tokenfrontBQ);
    }
    if(tokenBackBQ.userId){
        saveOrUpdate(env, tokenBackBQ);
    }
}

initAndUpdateToken();

if(window.location.href.indexOf('doc.html')>-1){
    let targetInput = null;

    var style = document.createElement('style');
    style.innerHTML = '.selectToken option:hover { background-color: #ccdfca !important} input{background: #f0f0f0;cursor: pointer;}';
    document.head.appendChild(style);

    document.body.addEventListener('click', function(event) {
        if (event.target.tagName.toLowerCase() === 'input' && '请求头内容'==event.target.getAttribute('placeholder')) {
            targetInput = event.target;
            var x = event.clientX;
            var y = event.clientY;

            chrome.storage.local.get(["DEV_F_HT","DEV_B_HT","TEST_F_HT","TEST_B_HT", "DEV_F_BQ","DEV_B_BQ","TEST_F_BQ","TEST_B_BQ"]).then((result) =>  {
        
                if(!result.DEV_F_HT && !result.DEV_B_HT && !result.TEST_F_HT && !result.TEST_B_HT
                    && !result.DEV_F_BQ && !result.DEV_B_BQ && !result.TEST_F_BQ && !result.TEST_B_BQ){
                    return;
                }

                var popupElement = document.createElement('div');
                // popupElement.style.position = 'absolute';
                popupElement.style.zIndex = 999;
                popupElement.style.cursor = 'pointer';
                popupElement.className = 'hover-effect';
                popupElement.id = 'toastToken';
                let i = 0;
                if(result.DEV_F_HT){
                    i = showItemHandle(result.DEV_F_HT, popupElement, '航天开发环境前台', i++);
                }
                if(result.DEV_B_HT){
                    i = showItemHandle(result.DEV_B_HT, popupElement, '航天开发环境后台', i++);
                }
                if(result.TEST_F_HT){
                    i = showItemHandle(result.TEST_F_HT, popupElement, '航天测试环境前台', i++);
                }
                if(result.TEST_B_HT){
                    i = showItemHandle(result.TEST_B_HT, popupElement, '航天测试环境后台', i++);
                }

                if(result.DEV_F_BQ){
                    i = showItemHandle(result.DEV_F_BQ, popupElement, '兵器开发环境前台', i++);
                }
                if(result.DEV_B_BQ){
                    i = showItemHandle(result.DEV_B_BQ, popupElement, '兵器开发环境后台', i++);
                }
                if(result.TEST_F_BQ){
                    i = showItemHandle(result.TEST_F_BQ, popupElement, '兵器测试环境前台', i++);
                }
                if(result.TEST_B_BQ){
                    i = showItemHandle(result.TEST_B_BQ, popupElement, '兵器测试环境后台', i++);
                }

                // popupElement.style.left = x + 'px';
                // popupElement.style.top = y + 'px';
                popupElement.style.fontSize = '18px';
                popupElement.className = 'selectToken';
                removeToast();
                targetInput.parentNode.appendChild(popupElement);
                // document.body.appendChild(popupElement);
            });
        }else{
            if(event.target.parentNode.id == 'toastToken'){
                if(targetInput != null){
                    targetInput.value = event.target.token;
                    changeReactInputValue(targetInput, event.target.token);
                }
            }
            removeToast();
        }
    });
}

function showItemHandle(array, popupElement, title, j){
    if(!array || array.length === 0 || !Array.isArray(array)){
        return;
    }
    array.sort((a, b) => {
        let at = a.time || 0;
        let bt = b.time || 0;
        return bt - at;
    });
    for (let i = 0; i < array.length; i++) {
        popupElement.appendChild(getShowItem(array[i], i==0 ? title : '------------------------', j++));
    }
    return j;
}

function saveOrUpdate(env, token) {
    // console.log('check token ', token);
    chrome.storage.local.get([token.env]).then((result) => {
        let map = null;
        if(!result[token.env] || result[token.env].size === 0){
            map = new Array();
        }else{
            map = result[token.env];
        }
        token.time = (new Date()).getTime();

        let index = -1;
        for (let i = 0; i < map.length; i++) {
            if(map[i].userId == token.userId){
                index = i;
                break;
            }
        }
        if(index > -1){
            map[index] = token;
        }else{
            map.push(token);
        }
        
        let obj = {};
        obj[token.env] = map;
        // console.log(obj);
        chrome.storage.local.set(obj).then(() => {
            // console.log('更新token记录成功：userId ' + token.userId + ' | token ' + token.token + ' | env ' + token.env);
        });
    });
}

function getShowItem(item, env, i){
    let color = 'background: #d7ba94;color: white;:hover{background: #00b5e5;}';
    let color2 = 'background: #84a0b9;color: white;:hover{background: #00b5e5;}';

    let optionElement = document.createElement('option');
    optionElement.textContent = env +' | '+item.userId+' | ' + item.token + ' | ' + (new Date(item.time)).toLocaleString('zh-CN');
    optionElement.value = item.token;
    optionElement.userId = item.userId;
    optionElement.token = item.token;
    optionElement.className = 'op'
    optionElement.style = (i % 2 ==0 ? color : color2);
    return optionElement;
}

function removeToast(){
    let toast = document.getElementById('toastToken');
    if(toast!=null){
        toast.remove();
    }
}

function changeReactInputValue(inputDom,newText){
    let lastValue = inputDom.value;
    inputDom.value = newText;
    let event = new Event('input', { bubbles: true });
    event.simulated = true;
    let tracker = inputDom._valueTracker;
    if (tracker) {
      tracker.setValue(lastValue);
    }
    inputDom.dispatchEvent(event);
}

const isSupportCookieStore = typeof cookieStore === 'object' && location.protocol === 'https:';
if(isSupportCookieStore){
    cookieStore.addEventListener('change', (event) => {
        // const type = event.changed.length ? 'change' : 'delete';
        // console.log('页面监听到cookie变更，执行token检查更新');
        initAndUpdateToken();
    });
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    // cookie 变更
    if (request.type === "cookieChange") {
    //   console.log("Received a cookieChange from the background script ");
      initAndUpdateToken();
    }
    // 打开本地页面
    if (request.menuItemId) {
        switch (request.menuItemId) {
          case 'openLocal':
            openLocal();
            break;
          case 'openLocalThisPage':
            openLocalThisPage();
            break;
          default:
            url = 'https://www.baidu.com/s?wd=';
        }
      }
  });

  // 打开本地页面
  function openLocal(){
    let targetUrl = window.location.href;
    let splitStr = targetUrl.split('//');
    window.open(splitStr[0] + '//local.' + splitStr[1]);
  }

  // 打开本地页面-当前页
  function openLocalThisPage(){
    let targetUrl = window.location.href;
    let splitStr = targetUrl.split('//');
    window.location.href = splitStr[0] + '//local.' + splitStr[1];
  }